#include "head.h"
#include <iostream>
#include <sys/socket.h>

using std::cout;
using std::endl;

int main()
{
    //对于SIGPIPE信号的处理方式设置为直接忽略掉
    signal(SIGPIPE, SIG_IGN);

    //1. 创建监听套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    cout << "sfd:" << sfd << endl;
    ERROR_CHECK(sfd, -1, "socket");

    int on = 1;
    int ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
    ERROR_CHECK(ret, -1, "setsockopt");
    ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
    ERROR_CHECK(ret, -1, "setsockopt");
    
    //2. 服务器绑定网络地址
    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8000);
    serveraddr.sin_addr.s_addr = inet_addr("192.168.30.129");

    ret = bind(sfd, 
        (const struct sockaddr*)&serveraddr, sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "bind");

    //3. 进行监听
    ret = listen(sfd, 1);
    cout << "server is listening.\n";

    int newFd = accept(sfd, NULL, NULL);
    cout << "newFd " << newFd << endl;
    ERROR_CHECK(newFd, -1, "accept");

    sleep(3);//先休眠3秒钟

    const char * data = "hello, client";
    ret = send(newFd, data, strlen(data), 0);
    cout << "1 send " << ret << " bytes." <<endl;

    ret = send(newFd, data, strlen(data), 0);
    perror("send");
    cout << "2 send " << ret << " bytes." <<endl;

    ret = send(newFd, data, strlen(data), 0);
    perror("send");

    cout << "3 send " << ret << " bytes." <<endl;

    return 0;
}
